#include <stdio.h>
#include "kfifo.h"
#include "main.h"	
#include "msg.h"
#include "key.h"
#include "tim.h"
#include "sw_timer.h"
#include "hall.h"


//HALL 	PA0
//HIGH  open box
//LOW	close box

static uint8_t hall_state = 0xff;
static uint8_t hall_timer = 0xff;
static uint8_t hall_count = 0;
static uint8_t new_state = 0xff;

static uint8_t app_hall_get_level(void)
{
	if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0))
		return HALL_OPEN;
	else
		return HALL_CLOSE;
}

uint8_t app_hall_get_state(void)
{
	return hall_state;
}


void app_hall_timer_callback(void)
{
    uint8_t state = app_hall_get_level();

    if(new_state == state)
        hall_count++;
    else
        hall_count = 0;

    if(hall_count < 3)
        return;

    if(hall_timer != 0xff)
        hall_timer = sw_timer_stop(hall_timer);
     
    if(hall_state == new_state)
        return;
    
    hall_state = new_state;
	if(hall_state == HALL_OPEN)
	{
		//BOX_LOG("hall open box\n");
		app_msg_send(MSG_OPEN_BOX);
	}
	else
	{
		//BOX_LOG("hall close box\n");
		app_msg_send(MSG_CLOSE_BOX);
	}
}


void app_hall_handle(void)
{
	new_state = app_hall_get_level();

    //BOX_LOG("\nhall handle: %d, %d, %d\n", new_state, hall_state, hall_timer);
    
	if(new_state == hall_state && hall_timer == 0xff)
		return;

    hall_count = 0;
    
    if(hall_timer != 0xff)
        sw_timer_stop(hall_timer);
    hall_timer = sw_timer_start(50, 1, app_hall_timer_callback);
}

void app_hall_init(void)
{
	hall_state = app_hall_get_level();
    if(hall_state == HALL_OPEN)
		app_msg_send(MSG_OPEN_BOX);
	else
		app_msg_send(MSG_CLOSE_BOX);
}

void app_hall_deinit(void)
{
    
}


